package com.ustcinfo.study.hive.r4.shihonghong;

import java.sql.*;

/**
 * Describe:  hive连接，并执行HiveSql
 * Author: shihonghong
 *
 */
public class HiveConnection {

    // hive链接地址
    private static String url = "jdbc:hive2://nodex002:10000/default";

    //hive用户名
    private static String userName = "root";

    // hive密码
    private static String passwd = "";

    // hive 驱动
    private static String driver = "org.apache.hive.jdbc.HiveDriver";

    private static Connection connection = null;
    private static Statement statement = null;
    private static ResultSet resultSet = null;


    // 创建内部表member sql
    private static String createSql = "create table namecount(ip string,domain_name string,access_time tinyint,target_ip string,status int)row format delimited fields terminated by '#' ";
    // 加载数据到member sql
    private static String localDataSql = "load data local inpath '/home/ustcinfo/dnsSample' into table namecount ";

    // 统计出domain_name'number
    private static String countSql = "select domain_name,count(*) c from namecount group by domain_name";




    public static void main(String[] args) throws SQLException {

        //  加载hive驱动
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            System.out.println("驱动加载失败");
            e.printStackTrace();
        }

        try {
            // 连接hive
            connection = DriverManager.getConnection(url, userName, passwd);
            if (connection != null) {
                System.out.println("hive 连接成功");
            } else {
                System.out.println("hive 连接失败");
            }

            statement = connection.createStatement();

            statement.execute(createSql);
            statement.execute(localDataSql);
            resultSet = statement.executeQuery(countSql);
            while (resultSet.next()) {               //printout data
                System.out.println(resultSet.getString("domain_name")+":"+resultSet.getInt("c"));
            }

        } catch (SQLException e) {
            e.printStackTrace();
            System.exit(1);
        } finally {
            if(resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        }


    }







}
